package com.personal.server.impl;

import com.personal.mapper.UserMapper;
import com.personal.pojo.LoginInfo;
import com.personal.pojo.User;
import com.personal.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServerInfo implements com.personal.server.UserServer {

    @Autowired
    private UserMapper userMapper;


    @Override
    public LoginInfo login(User user) {
        User u = userMapper.login(user);
        if(u != null){
            Integer identify = u.getIdentify();
            log.info("{}登录成功,身份为：{}", u.getName(),identify == 0 ? "游客" : identify == 1 ? "管理员" : "普通用户");
            //生成token
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", u.getId());
            claims.put("name", u.getName());
            String jwt = JwtUtils.generateToken(claims);
            return new LoginInfo(u.getId(),u.getName(),jwt);
        }
        return null;
    }

    @Override
    public boolean register(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        int u = userMapper.register(user);
        if(u == 0){
            log.info("注册失败");
            return false;
        }
        log.info("注册成功");
        return true;
    }
}
